<template>
  <a-spin :spinning="loading">
    <a-card>
      <section slot="title">
        客诉列表
      </section>
      <a-row :gutter="16" type="flex">
        <a-col :span="8">
          <section class="flex items-center">
            <span class="label">平台订单号：</span>
            <a-input
              class="flex-1"
              @keyup.enter="search"
              allow-clear
              placeholder="请输入平台订单号"
              :max-length="100"
              v-model="orderId"/>
          </section>
        </a-col>
        <a-col :span="8">
          <section class="flex items-center">
            <span class="label">状态：</span>
            <a-select
              class="flex-1"
              @change="getData"
              allow-clear
              placeholder="请选择状态"
              v-model="status"
            >
              <a-select-option v-for="item in complaintsStatusEnums" :key="item.value" :value="item.value">{{ item.name }}</a-select-option>
            </a-select>
          </section>
        </a-col>
        <a-col :span="8">
          <a-button class="mx-8" type="primary" @click="search">查询</a-button>
          <a-button @click="reset">重置</a-button>
        </a-col>
        <a-col :span="8" class="mt-16">
          <section class="flex items-center">
            <span class="label">联系方式：</span>
            <a-input
              class="flex-1"
              @keyup.enter="search"
              allow-clear
              placeholder="请输入投诉人联系方式"
              :max-length="100"
              v-model="phone"/>
          </section>
        </a-col>
        <!--<a-col :span="8" class="mt-16">-->
          <!--<section class="flex items-center">-->
            <!--<span class="label">创建日期：</span>-->
            <!--<a-range-picker-->
              <!--class="flex-1"-->
              <!--allow-clear-->
              <!--show-time-->
              <!--placeholder="请选择创建日期"-->
              <!--v-model="createTimeArr"-->
              <!--@ok="getData"-->
            <!--/>-->
          <!--</section>-->
        <!--</a-col>-->
        <a-col :span="8" class="mt-16">
          <section class="flex items-center">
            <span class="label">服务商：</span>

            <a-select
            class="flex-1"
              allow-clear
              show-search
              labelInValue
              @change="getData"
              v-model="vendorId"
              placeholder="请选择服务商"
              :loading="selectConfig.searchLoading"
              @focus="focus"
             @search="searchData"
             :filter-option="filterOption"
             @popupScroll="popupScroll"
            >
              <a-select-option v-for="item in vendorList" :value="item.id" :key="item.id">{{
                item.name
              }}</a-select-option>
          
            </a-select>


          </section>
        </a-col>
        <a-col :span="8" class="mt-16">
          <section class="flex items-center">
            <span class="label">来源渠道：</span>
			<sourceChannel placeholder="请选择会员渠道"
			        v-model="channelId" isShow="true" platform="true"
			        :options="{ allowClear: true }"
			        @change="getData" class="flex-1 overflow-hidden" />
           <!-- <a-select
              class="flex-1"
              @change="getData"
              allow-clear
              placeholder="请选择来源渠道"
              v-model="channelId"
            >
							<a-select-option :value="0">平台录入</a-select-option>
              <a-select-option v-for="item in channelData" :key="item.id" :value="item.id">{{ item.name }}</a-select-option>
            </a-select> -->
          </section>
        </a-col>
      </a-row>
      <a-button class="mt-16" v-if="$permissionJudge('CustomerComplaintsAdd')" @click="showModal = true" type="primary" icon="plus">新建</a-button>
      <a-table
        class="mt-16"
        row-key="id"
        :columns="columns"
        :data-source="data"
        :scroll="scroll"
        :pagination="pagination"
      >
        <template #orderId="id, data">
          <section>
            <a-tag v-if="data.channelName" :color="data.channelColor || '#1890FF'">{{ data.channelName }}</a-tag>
						<router-link :to="{name: 'OrderList', params: data}">{{ id }}</router-link>
					</section>
          <section class="mt-6 text-gray">创建：{{ data.orderCreateTime }}</section>
        </template>
        <template #complaintDetails="complaintDetails">
          <a-tooltip :title="complaintDetails">
            <section class="overflow">{{ complaintDetails }}</section>
          </a-tooltip>
        </template>
        <template #processingResult="processingResult, data">
          <a-tooltip :title="processingResult">
            <section class="overflow">
              <a @click="$refs.handleCustomerComplaints.view(data.id)" href="javascript:;">{{ processingResult }}</a>
            </section>
          </a-tooltip>
        </template>
        <template #enable="val, data">
          <section @click.stop>
            <a-switch
              v-if="$permissionJudge('SetUserStatus')"
              :disabled="data.isSystemUser"
              :checked="data.isStop === 0"
              @change="setUserStop(data)"/>
          </section>
        </template>
        <template #action="val, data, index">
          <section v-if="data.status !== 2">
            <template v-for="(item, index) in buttons">
              <a href="javascript:;" :class="{gray: !!data.channelId && item.action === 'editComplaints', 'cursor-not-allowed': !!data.channelId && item.action === 'editComplaints'}" :key="item.permission" @click="handleAction(item.action, data)">{{ item.name }}</a>
              <a-divider v-if="index !== buttons.length - 1" type="vertical"/>
            </template>
          </section>
        </template>
      </a-table>
      <a-modal
        v-model="showModal"
        width="660px"
        :title="`${isEdit ? '修改' : '新增'}客诉信息`"
        :confirm-loading="loading"
        @cancel="cancel"
        @ok="confirmComplaints"
      >
        <a-form v-if="showModal" :form="form" class="inline-form">
          <a-row :gutter="16">
            <a-col :span="12">
              <a-form-item label="关联订单">
                <a-input
                  placeholder="请输入关联订单ID"
                  :max-length="16"
                  :disabled="isEdit || isAdd"
                  v-decorator="[
                    'orderId',
                    {rules: [{required: true, whitespace: true, validator: orderValidator}]}
                  ]"
                />
                <a-input type="hidden" v-decorator="['id']"/>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="优先级">
                <a-select
                  placeholder="请选择优先级"
                  v-decorator="[
                    'priorityLevel',
                    {rules: [{required: true, message: '请选择优先级'}]}
                  ]"
                >
                  <a-select-option v-for="item in priorityLevelEnums" :key="item.value" :value="item.value">{{ item.name }}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="投诉时间">
                <a-date-picker
                  class="w-full"
                  placeholder="请选择投诉时间"
									:disabled-date="disabledDate"
                  v-decorator="[
                    'complaintsTime',
                    {rules: [{required: true, message: '请选择投诉时间'}]}
                  ]"
                />
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item style="display: block;" label="投诉内容">
                <a-textarea
                  rows="4"
                  :max-length="300"
                  placeholder="请输入投诉内容"
                  v-decorator="[
                    'complaintDetails',
                    {rules: [{required: true, whitespace: true, message: '请输入投诉内容'}]}
                  ]"
                />
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
      </a-modal>
      <HandleCustomerComplaints @getData="getData" ref="handleCustomerComplaints"/>
    </a-card>
  </a-spin>
</template>
<script>
import { tableMixins } from '@/utils/mixins'
import sourceChannel from '@/components/sourceChannel'
import { getComplaintList, addComplaints, editComplaints } from '@/api/order/complaints'
import {getAllVendors} from '@/api/vendor'
import HandleCustomerComplaints from './HandleCustomerComplaints'
import moment from 'moment'
import { searchVendor} from '@/api/vendor'
import { debounce} from 'lodash'
const buttons = [
  {name: '编辑', action: 'editComplaints', permission: 'CustomerComplaintsEdit'},
  {name: '处理', action: 'handleCustomerComplaints', permission: 'CustomerComplaintsProcessing'},
  {name: '推送', action: 'handlePush', permission: 'CustomerComplaintsPush'}
]
export default {
  name: 'CustomerComplaintsList',
  components: { HandleCustomerComplaints,sourceChannel },
  mixins: [tableMixins],
  data() {
    return {
      showModal: false,
      loading: false,
      isAdd: false,
      isEdit: false,
      storeId: undefined,
      orderId: '',
      channelId: undefined,
      phone: '',
      createTimeArr: [undefined, undefined],
      complaintsStatusEnums: [],
      priorityLevelEnums: [],
      channelData: [],
      selectConfig:{
        searchKey: '',
        searchLoading: false,
        data: [],
        total:0,
        pageNum:1,
        rowsNum:10,
      },
      columns: [
        { dataIndex: 'orderId', width: 220, align: 'center', title: '关联订单', scopedSlots: { customRender: 'orderId' } },
        {
          dataIndex: 'complaintDetails',
          align: 'center',
          ellipsis: true,
          width: '25%',
          title: '投诉内容',
          scopedSlots: { customRender: 'complaintDetails' }
        },
        {
          dataIndex: 'processingResult',
          align: 'center',
          ellipsis: true,
          width: '25%',
          title: '处理结果',
          scopedSlots: { customRender: 'processingResult' }
        },
        { dataIndex: 'priorityLevelName', width: 100, title: '优先级', align: 'center' },
	      { dataIndex: 'channelName', width: 100, title: '投诉来源', align: 'center', customRender: channelName => channelName || '平台录入' },
        { dataIndex: 'vendorName', width: 140, title: '服务商', align: 'center' },
        { dataIndex: 'statusName', width: 100, title: '状态', align: 'center' },
        { dataIndex: 'complaintsTime', align: 'center', width: 160, title: '投诉时间' },
        { dataIndex: 'processingTime', align: 'center', width: 160, title: '处理时间' },
        { dataIndex: 'action', fixed: 'right', width: 140, align: 'center', title: '操作', scopedSlots: { customRender: 'action' } }
      ],
      data: [],
      form: this.$form.createForm(this)
    }
  },
  computed: {
    buttons() {
      return buttons.filter(e => this.$permissionJudge(e.permission))
    },
    scroll() {
      return {x: this.data.length === 0 ? undefined : 1300}
    }
  },
  async mounted() {
    const params = this.$route.params
    if (params.id) {
      if (params.isAdd) {
        this.isAdd = true
        this.showModal = true
        this.$nextTick(() => {
          this.form.setFieldsValue({
            orderId: params.id
          })
        })
      } else {
        this.orderId = `${params.id}`
      }
    }
    this.complaintsStatusEnums = await this.$utils.getDictList('ComplaintsStatus')
    this.priorityLevelEnums = await this.$utils.getDictList('PriorityLevel')
    this.searchData = debounce(this.searchData, 100);
    // this.$utils.getChannel().then(data => this.channelData = data)
    this.getData()
  },
  methods: {
    filterOption(input, option) {
      return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
    },
    getVendorList(){
      this.selectConfig.searchLoading = true
      searchVendor({
            search: this.selectConfig.searchKey.trim(),
            rowsNum: this.selectConfig.rowsNum,
           pageNum: this.selectConfig.pageNum,
            isEnabled: true
          }).then((data) => {
            this.selectConfig.searchLoading = false
            const {items, rowCount} = data
              this.vendorList = this.selectConfig.pageNum === 1 ? items : [...this.vendorList.concat(items)]
           
           this.selectConfig.total = rowCount
          }
        ).catch(() => this.selectConfig.searchLoading = false)
    },
    searchData(searchKey) {
        this.selectConfig.searchKey = searchKey
        this.selectConfig.pageNum = 1
        this.getVendorList()
      },
    focus() {
        this.selectConfig.searchKey = ''
        this.selectConfig.pageNum = 1
        this.getVendorList()
      },
      popupScroll:debounce (function (e) {
        const {scrollHeight, scrollTop, clientHeight} = e.target
        if (scrollHeight - scrollTop === clientHeight) {
          if (!(this.vendorList.length === this.selectConfig.total)){
            this.selectConfig.pageNum++
            this.getVendorList()
          }
        }
      },500),
    search() {
      this.pageNum = 1
      this.getData()
    },
    reset() {
      this.pageNum = 1
      this.orderId = ''
      this.channelId = undefined
      this.phone = ''
      this.vendorId=undefined
      this.status = undefined
      this.createTimeArr = [undefined, undefined]
      this.getData()
    },
    getData() {
      this.loading = true
      getComplaintList({
        orderId: this.orderId.trim(),
        pageNo: this.pageNum,
        pageSize: this.rowsNum,
        status: this.status,
	      orderPhone: this.phone,
        channelId: this.channelId,
        vendorId: this.vendorId?this.vendorId.key: undefined,
        createTimeStart: this.$utils.getStartTime(this.createTimeArr[0]),
        createTimeEnd: this.$utils.getEndTime(this.createTimeArr[1])
      }).then(res => {
        res.items.forEach(item => {
          item.statusName = this.$utils.getEnumName(this.complaintsStatusEnums, item.status)
          item.priorityLevelName = this.$utils.getEnumName(this.priorityLevelEnums, item.priorityLevel)
          item.processingTime = this.$utils.judgeTime(item.processingTime) ? item.processingTime : '暂无'
        })
        this.data = res.items
        this.total = res.rowCount
      }).finally(() => this.loading = false)
    },
    handleAction(action, data) {
	    if (!!data.channelId && action === 'editComplaints') return
      this[action](data)
    },
    handleCustomerComplaints({id}) {
      this.$refs.handleCustomerComplaints.edit(id)
    },
	  disabledDate(date) {
    	return date > moment()
		},
    editComplaints(data) {
      this.isEdit = true
      this.showModal = true
      this.$nextTick(() => {
        this.form.setFieldsValue({
          id: data.id,
          orderId: data.orderId,
          priorityLevel: data.priorityLevel,
          complaintsTime: moment(data.complaintsTime),
          complaintDetails: data.complaintDetails
        })
      })
    },
    confirmComplaints() {
      this.form.validateFields((err, values) => {
        if (!err) {
          const confirmFn = this.isEdit ? editComplaints : addComplaints
          this.confirmLoading = true
          confirmFn(this.$utils.trimValue(values)).then(() => {
            this.$message.success(`${this.isEdit ? '修改' : '新增'}成功！`)
            this.cancel()
            this.getData()
          }).finally(() => this.confirmLoading = false)
        }
      })
    },
    orderValidator(rule, value, callback) {
      const amount = (value ? `${value}` : '').trim()
      const isAmount = /^([1-9]\d*|[0]{1,1})$/
      if (!amount) {
        callback(new Error('请输入关联订单号'))
      }
      if (amount && !isAmount.test(amount)) {
        callback(new Error('请输入数字'))
      } else {
        callback()
      }
    },
    cancel() {
      this.isEdit = false
      this.isAdd = false
      this.showModal = false
      this.form.resetFields()
    }
  }
}
</script>
<style scoped>
  .label {
    width: 84px;
    text-align: right;
  }
  /deep/ .ant-table-body {
    overflow: auto!important;
  }
	.gray {
		color: #999
	}
</style>
